import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { UserAuthService } from '@core/services/user-auth.service';
import { ApiService } from '@core/services/http/api.service';
import * as CryptoJS from 'crypto-js';
import { MenuService } from '@core';
import { ApesMessageService } from '@shared/apes/message';

@Component({
  selector: 'index',
  templateUrl: './index.component.html',
  styleUrls: ['./index.component.scss'],
})
export class IndexComponent implements OnInit {

  dataList = [
    { link: 'pad/storeControl', label: '门店总控', color: '#baff94' },
  ];
  userId: string;
  posts = []; // 岗位列表
  currentPostName: string;

  constructor(private router: Router,
              private userAuthService: UserAuthService,
              public msg: ApesMessageService,
              private apiService: ApiService,
              private routeInfo: ActivatedRoute,
              private menuService: MenuService) {
  }

  ngOnInit() {
    //  解密
    this.routeInfo.queryParams.subscribe((params: Params) => {
      let value = CryptoJS.enc.Base64.parse(params['value']);
      value = value.toString(CryptoJS.enc.Utf8);
      // this.userId = value;
      this.goLogin(value);
    });

  }

  goLogin(userId: string) {
    const data = { 'userId': userId };
    if (userId) {
      this.apiService.post('aut.user.loginIgnorePassword', { 'body': JSON.stringify(data) })
        .subscribe((items) => {
          const resultData = items.user;
          resultData['post'] = resultData.posts[0];
          const userInfo = { 'token': items.sessionId, 'userAccount': resultData };
          this.posts = userInfo.userAccount.posts;
          this.currentPostName = userInfo.userAccount.post.name;
          this.userAuthService.storeUserInfo(JSON.stringify(userInfo));
        });
    } else {
      this.msg.error('用户信息缺失，请退出重新登录！'); // 该用户已禁用，请联系行政人员
    }

  }

  _onclick(link: string) {
    this.router.navigate([link]);
  }

  changePost(postId: string) {
    // 检查数据的正确性
    let currentPost = this.posts.filter((post) => post.id == postId);
    if (currentPost.length === 0)
      return;

    // 检查是否改变 post
    let userInfo = this.userAuthService.getUserInfoObj();
    let currentPostInfo = userInfo.userAccount.post;
    if (postId === currentPostInfo.id)
      return;


    // 重新请求后端刷新菜单
    this.apiService.post('aut.user.bindPost', { 'body': JSON.stringify({ post: { id: postId } }) }).subscribe(
      (body) => {
        this.menuService.clear();

        if (body) {
          this.menuService.add(body);
        }

        // 将当前的数据存入 storage 中
        userInfo.userAccount.post = currentPost[0];
        this.userAuthService.storeUserInfo(JSON.stringify(userInfo));

        this.currentPostName = currentPost[0].name;
      });
  }

}
